package com.example.sharedpreferencestest;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import javax.security.auth.login.LoginException;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button save = findViewById(R.id.save_data);
        Button get = findViewById(R.id.get_data);
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取SharedPreferences对象
                SharedPreferences sp = getSharedPreferences("data",MODE_PRIVATE);
                // 通过SharedPreferences对象的edit()方法获取对象
                SharedPreferences.Editor editor = sp.edit();
                editor.putInt("age",22);
                editor.putString("name","liu");
                editor.apply();
            }
        });
        get.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences sp = getSharedPreferences("data",MODE_PRIVATE);
                Log.d("MainActivity", "name: " + sp.getString("name","无"));
                Log.d("MainActivity", "age: " + sp.getInt("age",-1));
            }
        });
    }
}